package yuanshen;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.swing.JOptionPane;

public class Config {
	public static String server;
	public static String uid;
	public static String token;
	public static String combineStr;
	
	static {
		Properties pro = new Properties();
		InputStream is = null;
		
		try {
			is = new FileInputStream("config.txt");
			pro.load(is);
			uid = pro.getProperty("uid");
			token = pro.getProperty("token");
			server = pro.getProperty("server");
			combineStr = "{\"role_id\":\"" + uid + "\",\"server\":\"" + server + "\"}";
			is.close();
			if (uid.length() == 0 || token.length() == 0) {
				JOptionPane.showMessageDialog(null, "读取配置失败");
				System.exit(0);
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "config.txt出现问题");
			System.exit(0);
		}
	}
	
	public static String getDS() {
		int timestamp = (int)(new Date().getTime() / 1000);
		int randnum = getRandom(100000, 200000);
		String sign = "salt=xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs"+
					  "&t=" + timestamp + 
					  "&r="+ randnum + 
					  "&b="+ combineStr +
					  "&q=";
		sign = getMD5Str(sign);
		
		return timestamp + "," + randnum + "," + sign;
	}
	
	private static String getMD5Str(String str) {
        byte[] digest = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest  = md5.digest(str.getBytes("utf-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //16是表示转换为16进制数
        String md5Str = new BigInteger(1, digest).toString(16);
        return md5Str;
    }
	
	private static int getRandom(int min, int max) {
		Random r = new Random();
		int result = (int)(r.nextDouble() * (max - min + 1)) + min;
		return result;
	}
}
